package com.entrogy.controller;

import com.entrogy.bean.*;
import com.entrogy.config.Result;
import com.entrogy.service.AppraisalService;
import com.entrogy.service.CheckTimeService;
import com.entrogy.utils.DateUtils;
import com.entrogy.utils.StrUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 许红松
 * @date 2019/6/5 0005 下午 3:58
 */
@RestController
@RequestMapping("/CheckTime")
public class CheckTimeController {


    @Autowired
    private CheckTimeService checkTimeService;//考勤service 接口
    @Autowired
    private AppraisalService appraisalService;//考勤方向关联接口

    /*
     *
     * @param person_id
     * @param month
     * @return
     */
    @PostMapping(value = "/getInfoByThdid")
    public List<PassRecordBean> getInfoByThdid(String person_id, String month) {
        Map<String, Object> map = new HashMap<>();
        if (!StringUtils.isNotBlank(person_id)) {
            map.put("person_id", person_id);
        }
        if (!StringUtils.isNotBlank(month)) {
            map.put("month", month);
        }
        // 每天 的第一次 打卡记录
        List<PassRecordBean> list = checkTimeService.getInfoByThdid(map);
        getKaoqinTime(null, "pass_record_".concat(month), list, 1);
        return list;

    }

    /*
     * @param month
     * @param school_code
     * @return
     */
    // 按月查询考勤的状态 是否异常打卡次数 正常打卡次数，姓名，职位
    @ApiOperation(value = "分页获取查询每个人的打卡信息的月统计情况")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校ID", name = "school_code", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(value = "月份", name = "month", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(value = "当前页数", name = "page", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(value = "每页条数", name = "total", dataType = "int", paramType = "query", required = true)
    })
    @PostMapping("/getMonthData")
    private List<UserEntity> getMonthData(String month, Integer school_code) {
        // 先去判断有没有这个月的数据信息
        Map<String, Object> map = new HashMap<>();
        if (!StringUtils.isNotBlank(month)) {
            map.put("month", month);
        }
        if (null != school_code) {
            map.put("school_code", school_code);
        }
        int code = checkTimeService.checkMonthTable(map);
        // 如果没有则创建这个月的总统计表 再然后按月查询其状态
        if (code == 0) {
            // 没有创建 则创建表
            checkTimeService.createMonthTable(map);
        }
        // 按月查询每个人的打卡信息的月统计情况
        return checkTimeService.getPassRecordByMoth(map);
    }

    @ApiOperation(value = "分页获取按日获取考勤记录")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校ID", name = "school_code", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(value = "当前日期", name = "Date1", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(value = "当前页数", name = "currentPage", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(value = "每页条数", name = "pageSize", dataType = "int", paramType = "query", required = true)
    })
    @PostMapping("/selectDay")
    private List<CheckTime> selectDay(String Date1, Integer school_code) {
        Map<String, Object> map = new HashMap<>();
        String tableName = "pass_record".concat(Date1.replaceAll("-", ""));
        if (StringUtils.isNotBlank(Date1)) {
            map.put("tableName", tableName);
        }
        if (StringUtils.isNotBlank(Date1)) {
            map.put("Date1", Date1);
        }
        if (null != school_code) {
            map.put("school_code", school_code);
        }

        List<CheckTime> list = checkTimeService.selectDay3(map);
        return list;
    }

    @ApiOperation(value = "统计考勤记录")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校ID", name = "school_code", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(value = "起始日期", name = "Time1", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(value = "截止日期", name = "Time2", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(value = "当前页数", name = "page", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(value = "每页条数", name = "total", dataType = "int", paramType = "query", required = true)
    })
    @PostMapping("/getCountList")
    public Result getCountList(String Time1, String Time2, Integer school_code){
        Map<String, Object> map = new HashMap<>();

        if (StringUtils.isNotBlank(Time1)) {
            map.put("Time1", Time1);
        }
        if (StringUtils.isNotBlank(Time2)) {
            map.put("Time2", Time2);
        }
        if (!DateUtils.isThisTime(Time1)){
            return new Result().getResult(0,"该日期超出当月日期！",0,"");
        }
        if (!DateUtils.isThisTime(Time2)){
            return new Result().getResult(0,"该日期超出当月日期！",0,"");
        }
        if (null != school_code) {
            map.put("school_code", school_code);
        }
        List<CheckTime> list = checkTimeService.getCountList(map);
      /*  CheckTimeResult checkTimeResult=new CheckTimeResult();
        checkTimeResult.setList(list);*/
        return new Result().getResult(1,"查询成功！",1,list);
    }


    @ApiOperation(value = "月度统计")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校ID", name = "school_code", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(value = "起始日期", name = "Time1", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(value = "截止日期", name = "Time2", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(value = "当前页数", name = "page", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(value = "每页条数", name = "total", dataType = "int", paramType = "query", required = true)
    })
    @PostMapping("/getMonthList")
    public Result getMonthList(String Time1, String Time2, Integer school_code){
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(Time1)) {
            map.put("Time1", Time1);
        }
        if (StringUtils.isNotBlank(Time2)) {
            map.put("Time2", Time2);
        }
        if (!DateUtils.isThisTime(Time1)){
            return new Result().getResult(0,"该日期超出当月日期！",0,"");
        }
        if (!DateUtils.isThisTime(Time2)){
            return new Result().getResult(0,"该日期超出当月日期！",0,"");
        }
        if (null != school_code) {
            map.put("school_code", school_code);
        }
        List<CheckTimeResult> list = checkTimeService.getMonthList(map);

        return new Result().getResult(1,"查询成功！",1,list);
    }
    /**
     * @param date
     * @param tableName
     * @param lists
     * @param type
     */
    private void getKaoqinTime(String date, String tableName, List<PassRecordBean> lists, int type) {
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sFormat = new SimpleDateFormat("HH:mm");


        for (PassRecordBean passRecordBean : lists) {
            String morningTime = null;// 上午上班打卡时间
            String morningOutTime = null;// 上午下班打卡时间
            String afternoonTime = null;// 下午上班打卡时间
            String afternoonOutTime = null;// 下午下班打卡时间
            String nightTime = null;// 晚上上班打卡时间
            String nightOutTime = null;// 晚上下班打卡时间
            if (StrUtils.isNullOrEmpty(date)) {
                date = simpleDateFormat3.format(passRecordBean.getRecord_time());
            }
            Map<String, Object> map = new HashMap<>();
            map.put("user_Id", passRecordBean.getPerson_id());
            Map<String, Object> map1 = appraisalService.getshiftBypeople(map);
            // 查询出某个人 的打卡时间
            String now = DateUtils.GetNowDate().substring(0, 10);
            if (null != map1) {

                if (!StringUtils.isNotBlank(map1.get("shift1_Uptime").toString())) {
                    StringBuffer buf = new StringBuffer();
                    morningTime = buf.append(now).append(" ").append(map1.get("shift1_Uptime").toString()).append(":00").toString();
                }
                if (!StringUtils.isNotBlank(map1.get("shift1_Downtime").toString())) {
                    StringBuffer buf = new StringBuffer();
                    morningOutTime = buf.append(now).append(" ").append(map1.get("shift1_Downtime")).append(":00").toString();
                }
                if (!StringUtils.isNotBlank(map1.get("shift2_Uptime").toString())) {
                    StringBuffer buf = new StringBuffer();
                    afternoonTime = buf.append(now).append(" ").append(map1.get("shift2_Uptime")).append(":00").toString();
                }
                if (!StringUtils.isNotBlank(map1.get("shift2_Downtime").toString())) {
                    StringBuffer buf = new StringBuffer();
                    afternoonOutTime = buf.append(now).append(" ").append(map1.get("shift2_Downtime")).append(":00").toString();
                }
                if (map1.get("shift3_Uptime") != null && !"".equals(map1.get("shift3_Uptime"))) {
                    StringBuffer buf = new StringBuffer();
                    nightTime = buf.append(now).append(" ").append(map1.get("shift3_Uptime")).append(":00").toString();
                }
                if (map1.get("shift3_Downtime") != null && !"".equals(map1.get("shift3_Downtime"))) {
                    StringBuffer buf = new StringBuffer();
                    nightOutTime = buf.append(now).append(" ").append(map1.get("shift3_Downtime")).append(":00").toString();
                }
            }
            if (type == 1) { // 按月查看 的日期 封装
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                date = simpleDateFormat.format(passRecordBean.getRecord_time());
                passRecordBean.setCourse_id(date);// form bean couser_id -- >date
            }
            // 上午上班打卡 早上打卡 9点之前 否则为异常打卡
            Date passDate = passRecordBean.getRecord_time();
            if (morningTime != null && !morningTime.equals(passRecordBean.getRecord_time()) && !DateUtils.compare(morningTime, passRecordBean.getRecord_time().toString())) {
                passRecordBean.setIsNormal(1);
            } else if (afternoonTime != null && morningTime == null && !morningTime.equals(passRecordBean.getRecord_time())
                    && !DateUtils.compare(afternoonTime, passRecordBean.getRecord_time().toString())) { // 没有早班
                passRecordBean.setAfternoonIsNormal(1);
            }
            if (morningTime != null && (DateUtils.compare(morningTime, passRecordBean.getRecord_time().toString()) || DateUtils.compare(morningOutTime, passRecordBean.getRecord_time().toString()))) {
                passRecordBean.setMorningWork(getHoureAndMinuteAndSecond(passDate));
            } else if (afternoonTime != null && morningTime == null) {
                passRecordBean.setAfternoonWork(getHoureAndMinuteAndSecond(passDate));
            }

            // 上午下班打卡
            if (morningOutTime != null) {
                StringBuffer sf = new StringBuffer();
                map.put("morningOutTime", sf.append(date).append(" ").append(map1.get("shift1_Downtime")).toString());
                PassRecordBean passRecordBean3 = checkTimeService.getMorningOutTime(map);
                if (passRecordBean3 != null) {
                    Date passDate3 = passRecordBean3.getRecord_time();
                    if (afternoonTime == null) {// 没有午班
                        passRecordBean.setMorningOutWork(getHoureAndMinuteAndSecond(passDate3));
                    } else {// 有午班
                        if (DateUtils.compare(afternoonTime, passRecordBean3.getRecord_time().toString())) {// 没有在下午上班时间之前
                            passRecordBean.setMorningOutWork(getHoureAndMinuteAndSecond(passDate3));
                        }
                    }

                }

            }
            map.put("tableName", tableName);
            map.put("person_id", passRecordBean.getPerson_id());
            // 下午上班打卡 根据此人的ID 去数据库 查询 看看他在12:00-14:00 之间有没有2次以上的打卡 如果有 则以最后一次打卡时间计算
            // 如果没有则不予记录 打卡时间
            if (afternoonTime != null) {
                PassRecordBean passRecordBean1 = null;
                Map<String, Object> map2 = new HashMap<>();
                if (morningOutTime != null) { // 有上午打卡时间
                    StringBuffer sf = new StringBuffer();
                    map.put("morningOutTime", sf.append(date).append(" ").append(map1.get("shift1_Downtime")).toString());
                    map.put("afternoonTime", sf.append(date).append(" ").append(map1.get("shift2_Uptime")).toString());
                    passRecordBean1 = checkTimeService.getAfternoonTime(map);
                    if (passRecordBean1 != null) {
                        Date passDate2 = passRecordBean1.getRecord_time();
                        passRecordBean.setAfternoonWork(getHoureAndMinuteAndSecond(passDate2));
                    } // 没有上班打卡时间 则不用 管 进循环的时候 已经 有了
                }
            }
            // 下午下班打卡
            if (afternoonOutTime != null) {
                PassRecordBean passRecordBean2 = null;
                if (StrUtils.isNullOrEmpty(map1.get("shift3_Uptime").toString())) {// 没有加班时间
                    StringBuffer stf = new StringBuffer();
                    // 查询上午上班班时间后的最后一次打卡
                    map.put("nightOutWork", stf.append(date).append(" ").append(map1.get("shift2_Uptime")).toString());
                    passRecordBean2 = checkTimeService.getNightOutWork(map);
                } else {// 有加班时间
                    // 查询下午下班时间后的第一次打卡
                    StringBuffer stf = new StringBuffer();
                    map.put("afternoonOutWork", stf.append(date).append(" ").append(map1.get("shift2_Downtime")).toString());
                    passRecordBean2 = checkTimeService.getAfternoonOutTime(map);
                }
                if (passRecordBean2 != null) {
                    Date passDate4 = passRecordBean2.getRecord_time();
                    if (!(afternoonOutTime).equals(passRecordBean2.getRecord_time().toString()) && DateUtils.compare(afternoonOutTime, passRecordBean2.getRecord_time().toString())) {
//							passRecordBean.setIsNormal(1);
                        passRecordBean.setAfternoonWorkIsNormal(1);
                    }
                    passRecordBean.setAfternoonOutWork(getHoureAndMinuteAndSecond(passDate4));
                }
                if (!StrUtils.isNullOrEmpty(map1.get("shift3_Uptime").toString())) { // 有加班时间
                    // 晚上 加班上班打卡（在下午下班时间和加班上班时间之间有没有两次打卡 如果有则取最新的一次时间为下午下班打卡时间 以最后的时间作为加班上班打卡时间 否怎默认
                    // 加班上班时间未打卡）
                    StringBuffer stf = new StringBuffer();
                    map.put("morningOutTime", stf.append(date).append(" ").append(map1.get("shift2_Downtime")));
                    map.put("afternoonTime", stf.append(date).append(" ").append(map1.get("shift3_Uptime")));
                    PassRecordBean passRecordBean4 = checkTimeService.getAfternoonTime(map);
                    if (passRecordBean4 != null) {
                        Date passDate5 = passRecordBean4.getRecord_time();
                        passRecordBean.setAfternoonOutWork(getHoureAndMinuteAndSecond(passDate5));
                    }
                    // 晚上 加班下班 打卡（晚上下班时间后的最后一次打卡时间）
                    map.put("morningOutTime", stf.append(date).append(" ").append(map1.get("shift3_Downtime")));
                    PassRecordBean passRecordBean5 = checkTimeService.getNightOutWork(map);
                    if (null == passRecordBean5) {
                        passRecordBean.setNightWorkIsNormal(1); // 晚上加班 下班后 异常打卡 map1.get("shift3_Downtime")
                    } else {
                        Date passDate6 = passRecordBean5.getRecord_time();
                        passRecordBean.setAfternoonOutWork(getHoureAndMinuteAndSecond(passDate6));
                    }
                }
            }
        }
    }


    public static boolean sameTime(Date date1, Date date2, SimpleDateFormat sFormat) {
        return sFormat.format(date1).equals(sFormat.format(date2));
    }

    private String getHoureAndMinuteAndSecond(Date passDate) {
        return (passDate.getHours() > 9 ? "" + passDate.getHours() + "" : "0" + passDate.getHours() + "") + ":"
                + (passDate.getMinutes() > 9 ? "" + passDate.getMinutes() + "" : "0" + passDate.getMinutes()) + "" + ":"
                + (passDate.getSeconds() > 9 ? "" + passDate.getSeconds() + "" : "0" + passDate.getSeconds()) + "";
    }



    //月度总结查询
   /* public List<Map<String,Object>> */



}